#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
主机群组模型模块 - 为树形视图提供数据模型
"""

import logging
from typing import Dict, List, Any
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem

logger = logging.getLogger(__name__)

class HostGroupModel(QStandardItemModel):
    """主机群组数据模型"""
    
    def __init__(self, groups: List[Dict[str, Any]], parent=None):
        super().__init__(parent)
        self.setHorizontalHeaderLabels(["主机群组"])
        self.groups = groups
        self.build_tree()
    
    def build_tree(self):
        if not self.groups:
            return
        
        root_item = self.invisibleRootItem()
        group_dict = {}
        
        for group in self.groups:
            group_id = group.get("groupid")
            group_name = group.get("name")
            
            if not group_id or not group_name:
                continue
            
            path_parts = group_name.split("/")
            current_path = ""
            current_item = root_item
            
            for i, part in enumerate(path_parts):
                current_path += f"/{part}" if i > 0 else part
                
                if current_path in group_dict:
                    current_item = group_dict[current_path]
                else:
                    new_item = QStandardItem(part)
                    if i == len(path_parts) - 1:
                        new_item.setData(group_id, Qt.UserRole + 1)  # 修正UserRole偏移
                    current_item.appendRow(new_item)
                    group_dict[current_path] = new_item
                    current_item = new_item